import { Controller, Post, Body } from '@nestjs/common';
import { PinyinService } from './pinyin.service';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { ApiRes } from 'src/common/decorator/api-res.decorator';
import { AnalysisDto, AnalysisResDto } from './dto/analysis.dto';
import {
  // SearchWordsDto,
  // SearchWordsResDto,
  TranslateDto,
} from './dto/translate.dto';
import { Public } from 'src/common/decorator/public.decorator';
import { PinyinDto } from './dto/pinyin.dot';
import { TtsDto, TtsDtoResDto } from './dto/tts.dto';
import { TtsService } from './tts.service';
import { TranslateService } from './translate.service';
import { GptService } from './gpt.service';
import { SegmentationDto } from './dto/segmentation.dto';

@ApiTags('ai模块')
@Controller('app/ai')
export class AiController {
  constructor(
    private readonly pinyinService: PinyinService,
    private readonly ttsService: TtsService,
    private readonly translateService: TranslateService,
    private readonly gptService: GptService,
  ) {}

  @Post('/pinyin')
  @Public()
  @ApiOperation({
    summary: '将汉字转拼音',
  })
  @ApiRes(null, null, {
    type: 'array',
    items: { type: 'string', example: 'xīn' },
  })
  pinyin(@Body() data: PinyinDto) {
    return {
      data: this.pinyinService.transform(data.text).map((item) => item[0]),
    };
  }

  // @Post('/searchWords')
  // @ApiOperation({
  //   summary: 'AI查词, 翻译和用法',
  // })
  // @ApiBearerAuth()
  // @ApiRes(SearchWordsResDto)
  // async searchWords(@Body() data: SearchWordsDto) {
  //   console.log(data);
  //   // TODO

  //   this.gptService
  //     .post('/v1/chat/completions', {
  //       model: 'gpt-4o-mini',
  //       stream: true,
  //       messages: [
  //         {
  //           role: 'system',
  //           content: `根据用户输入的单词进行查词，获取翻译和用法。请以json的格式返回，比如{translation:"",usage:""}`,
  //         },
  //       ],
  //     })
  //     .then((res) => {
  //       console.log(res);
  //     });
  // }

  @Post('/analysis')
  @ApiOperation({
    summary: 'AI解析',
  })
  @ApiBearerAuth()
  @Public()
  @ApiRes(AnalysisResDto)
  async analysis(@Body() data: AnalysisDto) {
    console.log(data);
    const res = await this.gptService.post('/v1/chat/completions', {
      model: 'gpt-4o-mini',
      messages: [
        {
          role: 'system',
          content: `你是一个中文大师，请根据 “[输入的中文句子]” ，按照要求进行分析。
#grammar
如果是长难句对句中的常用的重点语法句式进行提取和简要英文解释。如果是很简单的句子，解释下句子的成分结构。
#collocations
根据原文对重点难点的词汇，提取句中可能对外国人不太了解的词汇，并进行简明的英文解释。
-----
请使用JSON返回格式,示例如下：
{"grammar":["有...约: This structure translates to 'have... appointment/invite'. It indicates that someone has made plans with friends to go out.","勾留了一日: This phrase means 'stayed for a day'. It emphasizes the duration of the stay.","便须: This phrase translates to 'must then'. It indicates necessity, showing that after staying, the speaker needs to take further actions.","因为...本已说定: This structure means 'because... had already agreed'. It introduces a reason for the father's decision not to send the speaker."],"collocations":["游逛 - to stroll or wander\\nRefers to the act of leisurely walking around and exploring a place.","渡江 - cross the Yangtze River\\nLiterally means 'to ferry across the river', which refers to traveling from one side of the Yangtze River to the other.","父亲 - father\\nA term for one's male parent.","茶房 - teahouse attendant\\nRefers to a person who works in a teahouse, often serving tea and providing hospitality."]}`,
        },
        {
          role: 'user',
          content: data.text,
        },
      ],
    });
    try {
      data = JSON.parse(res);
      return {
        code: res ? '000000' : '100000',
        data: data,
      };
    } catch (error) {
      return {
        code: '100000',
        data: null,
      };
    }
  }

  @Post('/translate')
  @ApiOperation({
    summary: '微软翻译',
  })
  @Public()
  @ApiRes(null, null, {
    type: 'array',
    items: { type: 'string' },
  })
  async translate(@Body() data: TranslateDto) {
    return {
      data: await this.translateService.translate(data.text),
    };
  }

  @Post('/tts')
  @ApiOperation({
    summary: 'tts， 根据文本获取音频',
  })
  @Public()
  @ApiRes(TtsDtoResDto)
  async tts(@Body() data: TtsDto) {
    return {
      data: await this.ttsService.txt2audio(
        {
          tex: data.text,
          voiceName: 'zh-CN-XiaoxiaoNeural',
        },
        'r',
      ),
    };
  }

  @Post('/segmentation')
  @ApiTags('导入文章')
  @ApiOperation({
    summary: '给文章分段',
  })
  @Public()
  @ApiRes(String)
  async segmentation(@Body() data: SegmentationDto) {
    const res = await this.gptService.post('/v1/chat/completions', {
      model: 'gpt-4o-mini',
      messages: [
        {
          role: 'system',
          content: `请按照以下规则对文本进行分段处理：
  1. 基础分段原则：
    - 每段控制在1-2个完整句子
    - 长句（超过40字）单独成段
    - 保持原有叙述顺序和逻辑
    - 每个分段之间都用中间空一行进行分割
  2. 对话处理规范：
□ 完整对话单位单独成段（包括说话人+冒号+引号内容）
□ 保留对话中的完整中文引号
示例：
张三说："这是今天的会议重点。"\n
李四敲着桌子补充道："我补充两点，第一...第二..."\n
  3. 格式要求：
    - 仅使用\n作为段落分隔符
    - 禁止添加任何符号/编号
    - 保持原始标点不变
  4. 特别注意事项：
▶ 不改变任何原文内容
▶ 中文引号保持完整（"「」"或"“”"）
▶ 复合句判断标准：以句号/感叹号/问号结尾
▶ 连续对话每人发言独立成段`,
        },
        {
          role: 'user',
          content: data.text,
        },
      ],
    });
    return {
      code: res ? '000000' : '100000',
      data: res,
    };
  }

  @Post('/article-translate')
  @ApiTags('导入文章')
  @ApiOperation({
    summary: '对文章进行翻译',
  })
  @Public()
  @ApiRes(String)
  async articleTranslate(@Body() data: SegmentationDto) {
    const res = await this.gptService.post('/v1/chat/completions', {
      model: 'gpt-4o-mini',
      messages: [
        {
          role: 'system',
          content: `根据已经分段后的中文文本翻译成纯英文，不修改原文本的分段格式，结合上下文语境，翻译内容，且翻译后需要每个分段保留原有空行分割。
  专项处理规则
■ 人名处理标准：
    - 全名拼音化（例：王晓明→Wang Xiaoming）
    - 单名加姓（例：王局长→Director Wang）`,
        },
        {
          role: 'user',
          content: data.text,
        },
      ],
    });
    return {
      code: res ? '000000' : '100000',
      data: res,
    };
  }
}
